package com.bds.btcdc.web.action;

import com.bds.btcdc.web.model.*;
import com.bds.btcdc.api.model.Result;
import com.bds.btcdc.web.service.*;
import com.bds.btcdc.web.utils.Const;
import com.bds.btcdc.web.utils.CookieUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class SetupAction extends BaseAction {
	Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private SetupService setupService;
	@Autowired
	private ExchangeService exchangeService;
	@Autowired
	private UserRateService userRateService;
	@Autowired
	private PairConverterService pairConverterService;
	@Autowired
	private StrategyOneService strategyOneService;
	@Autowired
	private StrategyManyService strategyManyService;


	@RequestMapping("/setup/keys/submit")
	@ResponseBody
	public Result keysSubmit(HttpServletRequest request,String api_exchange,String access_key, String secret_key) {
		Result rst = new Result();
		if (setupService.saveApiKeys(request, api_exchange, access_key, secret_key)) {
			rst.setCode(Const.SUC);
			rst.setMsg("设置成功");
		} else {
			rst.setCode(Const.FAIL);
			rst.setMsg("设置失败");
		}
		return rst;
	}

	@RequestMapping("/rate")
	public String rate(HttpServletRequest request, Model model) {
		Long user_id = CookieUtils.getUserIdfromCookie(request);
		List<TExchange> exchanges = exchangeService.getExchangeNoInUserRate(user_id);
		model.addAttribute("exchanges", exchanges);
		log.info("--------------------------跳转到费率设置------------------------");
		return "ftl/user/rate";
	}

	@RequestMapping("/rate_submit")
	@ResponseBody
	public String rate(HttpServletRequest request) {
		Long user_id = CookieUtils.getUserIdfromCookie(request);
		String code = request.getParameter("code");
		String rate = request.getParameter("rate");
		Result ret = new Result();
		if (StringUtils.isNotEmpty(code) && StringUtils.isNotEmpty(rate)) {
			try {
				TExchange exchange = exchangeService.getExchangeByCode(code);
				TUserRate userRate = userRateService.getByUserIdAndcode(user_id, code);
				// rate=交易所默认rate（没修改）
				BigDecimal rates = new BigDecimal(rate);
				if (rates.compareTo(exchange.getRate()) == 0) {
					log.info("修改值与交易所默认值相同");
					if (userRate != null) {
						userRateService.delete(userRate);
					}
					ret.setResult(Const.SUC, "修改成功！");
				} else {
					if (userRate == null) {// 新增
						userRate = new TUserRate();
						userRate.setCode(code);
						userRate.setState(1);
						userRate.setRate(rates);
						userRate.setUser_id(user_id);
					}
					userRate.setRate(rates);
					if (userRateService.update(userRate)) {
						ret.setResult(Const.SUC, "修改成功！");
					} else {
						ret.setResult(Const.FAIL, "修改时发生异常");
					}
				}
			} catch (Exception e) {
				log.error("修改时发生异常", e);
				ret.setResult(Const.FAIL, "修改时发生异常");
			}
		} else {
			ret.setResult(Const.FAIL, "前台传递的参数为空");
		}

		return "success_jsonpCallback" + "(" + this.parseJson(ret) + ")";
	}

	@RequestMapping("/exchange_rate")
	public String exchange_rate(HttpServletRequest request, Model model) {
		List<TPairConverter> allUsing = pairConverterService.getAllUsing();
		model.addAttribute("pairs", allUsing);
		log.info("--------------------------跳转到汇率设置------------------------");
		return "ftl/user/exchange_rate";
	}

	@RequestMapping("/exchange_rate_submit")
	@ResponseBody
	public String exchange_rate_submit(HttpServletRequest request) {
		String data = request.getParameter("data");
		Result ret = new Result();
		if (StringUtils.isNotEmpty(data)) {
			JSONArray objs = JSONArray.fromObject(data);
			try {
				for (int i = 0; i < objs.size(); i++) {
					JSONObject json = objs.getJSONObject(i);
					long id = Long.parseLong(json.getString("id"));
					Boolean useUserVal = json.getBoolean("useUserVal");
					TPairConverter pair = pairConverterService.getOneById(id);
					if (useUserVal) {// 使用用户数据
						BigDecimal update_val = new BigDecimal(json.getString("update_val"));
						BigDecimal re_update_val = new BigDecimal(json.getString("re_update_val"));
						pair.setUpdate_val(update_val);
						pair.setRe_update_val(re_update_val);
						pair.setUpdate_time(new Date());
					}
					pair.setUseUserVal(useUserVal);
					pairConverterService.updateOne(pair);
				}
				ret.setResult(Const.SUC, "修改成功！");
			} catch (Exception e) {
				log.error("修改时发生异常", e);
				ret.setResult(Const.FAIL, "修改时发生异常");
			}

		} else {
			ret.setResult(Const.FAIL, "前台传递的参数为空");
		}

		return "success_jsonpCallback" + "(" + this.parseJson(ret) + ")";
	}

	@RequestMapping("/set_api")
	public String setApi(Map<String, Object> map, HttpServletRequest request) {
		log.info("--------------------------跳转到API设置页面------------------------");
		return "ftl/user/set_api";
	}

	/**
	 * 量化交易设置   货币固定值
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/get_pair_stable_val")
	@ResponseBody
	public String get_pair_stable_val(HttpServletRequest request, Model model) {
		String exchange_code = request.getParameter("exchange_code");
		String en_coin_name = request.getParameter("en_coin_name");
		Result ret = new Result();
		if (StringUtils.isNotEmpty(exchange_code) && StringUtils.isNotEmpty(en_coin_name)) {
			Long user_id = CookieUtils.getUserIdfromCookie(request);
			try {
				StrategyManyArgs strategyManyArgs = strategyManyService.getOne(user_id, exchange_code, en_coin_name);
				if(strategyManyArgs!=null) {
					ret.setResult(Const.SUC,strategyManyArgs.getCoin_sum_threshold());
				}else{
					ret.setResult(Const.SUC,0);
				}
			} catch (Exception e) {
				log.error("发生异常", e);
				ret.setResult(Const.FAIL, "发生异常");
			}
		} else {
			ret.setResult(Const.FAIL, "前台传递的参数为空");
		}

		return "success_jsonpCallback" + "(" + this.parseJson(ret) + ")";
	}
	/**
	 * 策略参数设置  提交
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/strategy_submit",method = RequestMethod.POST)
	@ResponseBody
	public String strategy_submit(HttpServletRequest request, Model model) {
		String order_avg_price_threshold = request.getParameter("order_avg_price_threshold");
		String thld_start = request.getParameter("thld_start");
		String thld_end = request.getParameter("thld_end");
		String price_change_rate_threshold = request.getParameter("price_change_rate_threshold");
		String disk_yield_threshold = request.getParameter("disk_yield_threshold");
		String expected_yield_threshold = request.getParameter("expected_yield_threshold");
		String coin_stable_val = request.getParameter("coin_stable_val");
		String exchange_code = request.getParameter("exchange_code");
		String en_coin_name = request.getParameter("en_coin_name");
		Result ret = new Result();
		String msg="";
		//更新量化 固定金额
		Long user_id = CookieUtils.getUserIdfromCookie(request);
			try {
				if (StringUtils.isNotEmpty(exchange_code) && StringUtils.isNotEmpty(en_coin_name)) {
					StrategyManyArgs strategyManyArgs = strategyManyService.getOne(user_id, exchange_code, en_coin_name);
					if (strategyManyArgs == null) {
						strategyManyArgs=new StrategyManyArgs();
						strategyManyArgs.setUser_id(user_id);
					}
					strategyManyArgs.setExchange_code(exchange_code);
					strategyManyArgs.setEn_coin_name(en_coin_name);
					strategyManyArgs.setCoin_sum_threshold(BigDecimal.valueOf(Double.valueOf(coin_stable_val)));
					if(strategyManyService.update(strategyManyArgs)) {
						msg += "\n 量化 固定金额 更新成功";
					}else{
						msg += "\n 量化 固定金额 更新失败";
					}
				}
				//更新策略参数
				StrategyOneArgs strate_one = strategyOneService.getOneByUserId(user_id);
				if(strate_one==null){
					strate_one=new StrategyOneArgs();
				}
				strate_one.setUser_id(user_id);
				strate_one.setOrder_avg_price_threshold(BigDecimal.valueOf(Double.valueOf(order_avg_price_threshold)));
				strate_one.setThld_start(Double.valueOf(thld_start));
				strate_one.setThld_end(Double.valueOf(thld_end));
				strate_one.setPrice_change_rate_threshold(BigDecimal.valueOf(Double.valueOf(price_change_rate_threshold)));
				strate_one.setDisk_yield_threshold(BigDecimal.valueOf(Double.valueOf(disk_yield_threshold)));
				strate_one.setExpected_yield_threshold(BigDecimal.valueOf(Double.valueOf(expected_yield_threshold)));
				if(strategyOneService.update(strate_one)){
					msg += "\n 其他策略参数 更新成功";
				}else{
					msg += "\n 其他策略参数 更新失败";
				}
			} catch (Exception e) {
				log.error("更新发生异常", e);
				ret.setResult(Const.FAIL, "更新发生异常");
			}
			ret.setResult(Const.SUC, msg);
		return "success_jsonpCallback" + "(" + this.parseJson(ret) + ")";
	}



}
